package com.mckillion.icare;
//The purpose of this class is to show the location screen, this be used to set the home location.

//Import the required java packages.
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.mckillion.icare.R;

public class LocationalScreen extends Activity implements View.OnClickListener{

	//Declare the variables that will be used within the class.
	String longitude, latitude, provider, radiusString;
	TextView longVal, latVal, radiusVal;
	ImageButton backButton, homeButton, settingsButton;
	Button getLocationButton, setAsHomeButton;
	private ImageView infoButton;
	private TextView infoText;
	ToggleButton statusButton;
	Location location;
	SharedPreferences prefs;
	LocationManager locationManager;
	float radius;
	boolean checkPref, isEntered;
	
	//Override onCreate so that the code will run when the activity is started.
	@Override
    public void onCreate(Bundle savedInstanceState) {
        //Call to the super class.
		super.onCreate(savedInstanceState);
        
		 //Remove title and notification bars to give it an android feel.
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
		//Set the content layout to the locational_screen XML file.
        setContentView(R.layout.locational_screen);
                 
        //Create a GPS locationManager which will get the last known location
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        provider = LocationManager.GPS_PROVIDER;
        location = locationManager.getLastKnownLocation(provider);
        
        //Get preference value from sharedPreferences to show the current radius
        prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        radiusString = prefs.getString("fence_range", "10");
        radius = Float.valueOf(radiusString);
        
        //Set the TextViews above to match the TextViews in the XML file.
        longVal = (TextView) findViewById(R.id.long_val);
        latVal = (TextView) findViewById(R.id.lat_val); 
        radiusVal = (TextView) findViewById(R.id.radius_val);
        
        //Show the radius value on in this TextView
        radiusVal.setText(radiusString + " meters");
        
        //Set the declared buttons to match the buttons in the XML file.
        getLocationButton = (Button)findViewById(R.id.location_button);
        setAsHomeButton = (Button)findViewById(R.id.set_home);
        
        //Set the ToggleButton above to match the ToggleButton in the XML file.
        statusButton = (ToggleButton) findViewById(R.id.status_button);
        
        backButton = (ImageButton) findViewById(R.id.back_button);
        homeButton = (ImageButton) findViewById(R.id.home_button);
        settingsButton = (ImageButton) findViewById(R.id.settings_button);
        
    	infoButton=(ImageView)findViewById(R.id.imageView4);
    	
        //Set a listener for the information button
        infoButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//Use a layout inflater to open a pop-up window with the informational text.
				LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);  
				View popupView = layoutInflater.inflate(R.layout.info_popup, null);  
				final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT,  LayoutParams.WRAP_CONTENT);
			    
			    infoText = (TextView) popupWindow.getContentView().findViewById(R.id.info_text);
			    infoText.setText("This is the locational alerts screen." + "\n" + "\n" +
			    					"To enable/disable the service use the toggle button." + "\n" + "\n" +
			    					"The home location can be retrieved here. Turn on the GPS on your device and wait for a connection. " +
			    					" When a connection is established press 'Get Location' and 'Save as Home' to store the home location." +
			    					" The perimeter should be defined in the iCare settings." + "\n" + "\n" + "Press dismiss to close this message.");
			    
			    //create a dismiss button to close the pop-up window.
			    Button dismiss = (Button)popupView.findViewById(R.id.dismiss_button);
	            dismiss.setOnClickListener(new Button.OnClickListener(){
	            	@Override
	            	public void onClick(View v) {
	            		popupWindow.dismiss();
	            	}});
	               
	            //Put the pop-up window in the centre of the screen
	            popupWindow.showAtLocation(infoButton, Gravity.CENTER, 0, 0);
	   }});
        
        //Set a listener for the home button which starts the HomeScreen class
        homeButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(LocationalScreen.this, HomeScreen.class);
				startActivity(i);
			}
		});
        
        //Set a listener for the back button which starts the IntakeScreen class
        backButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(LocationalScreen.this, CalenderScreen.class);
				startActivity(i);
			}
		});
        
        //Set a listener for the settings button which starts the Settings class
        settingsButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(LocationalScreen.this, Settings.class);
				startActivity(i);
			}
		});
        
        //Get the current status from shared preferences
        checkPref = prefs.getBoolean("locational_pref", true);
               
        //If the status in preferences is "on" change the toggle button.
        if(checkPref == true){
        	statusButton.toggle();
        }	else
        	{	statusButton.toggle();
        		statusButton.toggle();
        	}
        
        //Set an actionListener for the ToggleButton
        statusButton.setOnClickListener(new Button.OnClickListener(){
    	    public void onClick(View arg0) {
    	    	 	//If the toggle button is pressed save the change to the shared preferences.
    	    		SharedPreferences.Editor editor = prefs.edit();
    	    		boolean checked = statusButton.isChecked();
                    editor.putBoolean("locational_pref", checked);
                    editor.commit();
                }});  
            
        //Set an actionListener for the refreshButton
        getLocationButton.setOnClickListener(new Button.OnClickListener(){
	    public void onClick(View arg0) {	    	
			if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) 
					&& locationManager.getLastKnownLocation(provider) != null)
				{	//if the GPS and turned on and there is a last known location update the textViews to show the location. 
				
	    			double latNum = location.getLatitude();
					double longNum = location.getLongitude();
					
					longitude = Double.toString(longNum);
					latitude = Double.toString(latNum);
					
					longVal.setText(longitude);
					latVal.setText(latitude);
	    		}	else
	    			{	//If GPS is off or has not found a signal show a toast notification.
	    				Context context = getApplicationContext();
			   		    CharSequence text = "Turn on the GPS and wait for a signal";
					    int duration = Toast.LENGTH_LONG;
					    Toast toast = Toast.makeText(context, text, duration);
					    toast.show();
	    			}
	    }});  
        
        //Set an actionListener for the homeButton
        setAsHomeButton.setOnClickListener(new Button.OnClickListener(){
    	    public void onClick(View arg0) 
    	    {	if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) 
					&& locationManager.getLastKnownLocation(provider) != null){
    	    	//Set the current location to home when this button is pressed.
    	    	//Get the location coordinates
    	    	double latNum = location.getLatitude();
				double longNum = location.getLongitude();
				
				//Change to strings.
				longitude = Double.toString(longNum);
				latitude = Double.toString(latNum);

				//Save to shared preferences
		        SharedPreferences.Editor editor = prefs.edit();
		        editor.putString("home_lat_pref", latitude);
		        editor.putString("home_long_pref", longitude);
		        editor.commit();
    	    }	else
			{	//If GPS is off or has not found a signal show a toast notification.
				Context context = getApplicationContext();
	   		    CharSequence text = "Get the current location first";
			    int duration = Toast.LENGTH_LONG;
			    Toast toast = Toast.makeText(context, text, duration);
			    toast.show();
			}
    	    }});  
    }
    	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{	//inflate the android option_menu from XML layout
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.option_menu, menu);
	    return true;
	}
	
	public void goHome(){
		//Create a method to handle a button press on the menu
		Intent i = new Intent(this, HomeScreen.class);
		startActivity(i);
	}
	
	public void showSettings(){
		//Create a method to handle a button press on the menu
		Intent i = new Intent(this, Settings.class);
		startActivity(i);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.menu_home:
	            goHome(); //if home button is pressed call the goHome method
	            return true;
	        case R.id.menu_settings:
	            showSettings(); //if settings button is pressed call the goHome method
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}

	public void onClick(View v) {
		//not used, imported as part of the class.
	}
	
	@Override
	public void onBackPressed() {
		//handle the back button being pressed
		Intent i = new Intent(LocationalScreen.this, CalenderScreen.class);
		startActivity(i);
	}
}